function [result, t, err] = datac(command, ctl, n)
%datac - main entry point for data analysis
% Oct/Nov 1998 P. Manis
% 2 Dec 1998 - moved most functions out of this source block
% to allow calling from other routines - better for auto analysis
% routines.
%
% Call with command (text; parsed below by switch),
% ctl is multifunctional - may be reference to the control matrix,
% or may be an argument (filename)
% n is usually the index into the control matrix for data operations
%
% this routine stores the CONTROL information as userdata in the main datac window so
% we can access it elsewhere
%
% CONTROL made a global variable for speed. 3/21/2002 Paul B. Manis.
%
persistent MATFILE NOTEFILE STEPS LASTPATH PATHFLAG DATAFILE OLDDIR
persistent WINDOWLIST
global CURRENT VOLTAGE WCHAN DFILE TMARKS STACK ALLCH
global CONTROL PATHS


result=[]; % define an output for this program...
t = [];
err = 0;
if(nargin < 1)
    h = findobj('Tag', 'datac_main');
    if(ishandle(h))
        disp('Can only start one instance of Datac!')
        return;
    end;
    command = 'initialize'; % make  initialization
    datac_paths; % set the paths in order...
    WINDOWLIST = [];

else
    if(~strfind(command, 'mouse')) % prevent mouse movements from calling all this stuff...
        [drive, path, extension] = getdriveext; % get the selected drive in the window
        if(isempty(LASTPATH))
            LASTPATH = extension; 
        end
        lookpath = LASTPATH; % use the previous path...
    end;
end;
if (nargin <= 1)
    n = 0;
end;


% main parse switch. Call program with "commands", which we handle here.
switch(command)

    % basic ops to access data easily
    case 'control'
        result = CONTROL;
        return;
    case 'sel'
        [sel, lmode] = listcontrol(PATHFLAG); % get the info from the selection
        result=CONTROL(sel);
        return;
    case 'getv'
        result = VOLTAGE;
        if(nargout > 1) t = make_time(DFILE); end;
        return;
    case 'geti'
        result = CURRENT;
        if(nargout > 1) t = make_time(DFILE); end;
        return
    case 'getw'
        result = WCHAN;
        if(nargout > 1) t = make_time(DFILE); end;
        return;
    case 'getdfile'
        result = DFILE;
        return

    case 'geti0'
        result = CURRENT(:,1)';
        return;

    case 'getv0'
        result = VOLTAGE(:,1)';
        return;

    case 'getnote'
        result=NOTEFILE;
        return;

    case 'getpath'
        result = LASTPATH;

    case 'getdatabase'
        result = MATFILE;

    case 'mouse_motion'
        datac_do_ptr(ctl, 0); % ctl should point to figure window...
    case 'mouse_down'
        datac_do_ptr(ctl, 1);
    case 'mouse_up'
        datac_do_ptr(ctl, 2);

    case 'Refresh' % refresh list on screen
        setlist;

    case 'initialize'
        main_screen;
        MATFILE = getsetini('get');	% read an ini file (if it exists...) - also reads the mat file listed therein
        PATHFLAG=0;	% use the paths in the file..
        DATAFILE = [];
        OLDDIR = cd(fileparts(which('datac.m'))); % find where we are

    case 'open'
        % two ways to do it - 'datac('open', 'filename') will try to open the file
        % datac('open') will use a gui to access it.
        erase_data_axes;
        result = 0;
        if(nargin<2)
            [drive, path, ext] = getdriveext;
            lookpath=strcat(path, ext);
            [filename, path] = uigetfile(lookpath, 'Open Data Files');
            if(~ischar(filename))
                QueMessage(sprintf('Unable to access file? %s - %s', path, filename), 1);
                result = 1;
                return;
            end
            setdriveext('path', path);
            LASTPATH = path;
            lookpath = path;
            truefile = strcat(path, filename);
        else
            truefile = ctl;
        end;

        truefile = slash4OS(truefile);

        [DFILE, data, err] = datac2mat(truefile, []); % just read the header - empty RL list
        if(err ~= 0)
            result = 1;
            return;
        end
        % read note file and paste information up on display
        [path, name, next] = fileparts(truefile);
        uext=upper(next);
        if(strcmp(uext, next))
            next='.NOT';
        else
            if(~strcmp(next, '.mat') && ~strcmp(next, '.abf'))
                next = '.not';
            end;

        end;
        notefile = fullfile(path, [name, next]);
        QueMessage(sprintf('Parsing Notefile: %s', notefile), 1);
        [NOTEFILE, note_err] = note_read(notefile);
        if(~note_err)
            pastenote(NOTEFILE, 'NoteFile', DFILE); % also puts up comment field...
        end
        QueMessage(sprintf('Opened file: %s', DFILE.filename));
        htag=findobj('Tag', 'Display');
        set(htag, 'Enable', 'on');
        htag=findobj('Tag', 'Scan');
        set(htag, 'Enable', 'on');
        DATAFILE = DFILE.filename;
        new_banner(DATAFILE, MATFILE);

    case 'readctl'
        % get the file name from the history list... 
        
    case 'auto_set'
        erase_data_axes;
        htag = findobj('Tag', 'NoteFile');
        sel = get(htag, 'Value');
        comboflag = 0; % 0 is do each individually ; otherwise, 1 is to combine the record lists.
        if(length(sel) > 1 && nargin < 2) % only ask if there are multiple entries
            button = questdlg('Combine all entries?',...
                'Combine entries','Yes','No','Help','No');
            if strcmp(button,'Yes')
                comboflag = 1;
            elseif strcmp(button,'No')
                comboflag = 0;
            elseif strcmp(button,'Help')
                QueMessage('Control list operation cancelled', 1);
                return;
            end
        end;
        if(~comboflag)
            for i = 1:length(sel)
                set(htag, 'Value', sel(i)); % select each individually
                v=get(htag, 'string');
                if(v(sel(i),1) == '>')
%                    sel = get(htag, 'Value');
                    [truefile, RL, mode, err] = getfileinfo('Note', DFILE, PATHFLAG);
                    if(err==1)
                        return;
                    end
                    watchon;
                        [DFILE, err] = readdatac_window(truefile, RL, 0, mode, 1);
                    watchoff;
                    if(err == 0)
                        DATAFILE = truefile;
                        new_banner(DATAFILE, MATFILE);
                    end;
                    datac('ToControl'); % add information to the control worksheet.
                    switch(DFILE.mode)
                        case {'cc', 'CC'}
                            set_ccpar;

                        case {'vc', 'VC'}
                            set_vcpar;
                        otherwise % let the user deal with it.
                    end;
                end;
            end;
            QueMessage(sprintf('%d Data entries added', length(sel)));
        else
            datac('display2'); % get the selected notefile entry
            datac('ToControl'); % add information to the control worksheet.
            switch(DFILE.mode)
                case {'cc', 'CC'}
                    set_ccpar;

                case {'vc', 'VC'}
                    set_vcpar;
                otherwise % let the user deal with it.
            end;
%             datac('ToControl'); % add information to the control worksheet.
%  
%             edit_control('edit');
%             edit_control('auto');
            datac('List_Dispatch', 1); % read the data from the screen
            toggle_display('data'); % show us the data.
            QueMessage(sprintf('%d Data entries combined', length(sel)));
        end;
          htag = findobj('Tag', 'NoteFile');
      if(~isempty(htag))
          set(htag, 'Value', sel); % restore selection.
      end;
        % dispatch reading manually
    case 'display'
        profile on
        erase_data_axes;
        [truefile, RL, mode] = getfileinfo('Manual', DFILE, PATHFLAG);
        truefile = slash4OS(truefile);
        h2 = findobj('Tag', 'Path');
        path = get(h2, 'String');
        try
            watchon;
            [DFILE, err] = readdatac_window(truefile, RL, 0, mode, 1);
            watchoff;
        catch
            watchoff;
        end;
        profile viewer

   % dispatch display by double clicking a line on the notefile abstract
    case 'display2'
        erase_data_axes;
        try
            htag = findobj('Tag', 'NoteFile');
            hf = findobj('Tag', 'datac_main');
            if(~ishandle(htag))
                QueMessage('Notefile Tag not found', 1);
                return;
            end
            mode = getdatamode;
            s=get(hf, 'SelectionType');
            if(nargin == 1 && strmatch(s, 'normal', 'exact')) % single click : do nothing
                %QueMessage('Single click');
                return;
            elseif(nargin > 1 || strmatch(s, 'open', 'exact')) % double click: operate on all...
                sel = get(htag, 'Value');
                [truefile, RL, mode, err] = getfileinfo('Note', DFILE, PATHFLAG);
                if(err==1)
                    QueMessage('Error getting file info from notefile');
                    return;
                end
                watchon;
                if(~isempty(CONTROL) && n > 0)
                    [DFILE, err] = readdatac_window(truefile, RL, n, mode, 1);
                else
                    [DFILE, err] = readdatac_window(truefile, RL, 0, mode, 1);
                end
                if(err)
                    QueMessage('Failed to read file ? ');
                end;
                watchoff;
                if(err == 0)
                    DATAFILE = truefile;
                    new_banner(DATAFILE, MATFILE);
                end;

            end
         catch
             watchoff;
             QueMessage('Error Displaying data from Notefile');
         end;


        % dispatch data read from the control list
    case 'List_Dispatch'
        % try
        %     profile on
        [bigsel, lmode] = listcontrol(PATHFLAG); % get the info from the selection
        if(nargin < 2 && lmode == 0 || isempty(bigsel)) % call with more than one arg to force read
            return; % "normal" does nothing, just leave selection
        else
            % nargin is at least 2 - use the nth (defined by ctl) selection...
            sel = bigsel(1);
            [pa fi ext] = fileparts(slash4OS(CONTROL(sel).path));
            hd = findobj('tag', 'driveflag_chkbx');
            dr_override = get(hd, 'value');
            if(dr_override)
                [dr pa2 ext2] = getdriveext;
                pa(1) = dr(1); % replace the drive letter
                CONTROL(sel).path = pa;
            end;

            truefile = parse_filename(CONTROL(sel).path, CONTROL(sel).filename); % get the filename like this...
            truefile = slash4OS(truefile);
            % check to see if file actually exists at intended location

            h = findobj('Tag', 'RecList');
            if(~check_field(CONTROL(sel),'reclist')) % If this field is present, it overrides the simple record list.
                RecList=sprintf('%d;%d/%d', number_arg(CONTROL(sel).recbeg), number_arg(CONTROL(sel).recend), number_arg(CONTROL(sel).skip));
            else
                RecList=CONTROL(sel).reclist;
            end
            set(h, 'String', RecList);

            [RL] = record_parse(RecList);
            QueMessage(sprintf('File: %s Recs: %s',truefile, RecList));
            mode = getdatamode;
            [DFILE, err] = readdatac_window(truefile, RL, sel, mode, 1);
            if(err == 0)
                DATAFILE = truefile;
                new_banner(DATAFILE, MATFILE);
            end;

            if(~check_field(CONTROL(sel),'NOTEFILE')) % if field does not exist...
                CONTROL(sel).NOTEFILE=[]; % create the field
            end;
            if(isempty(CONTROL(sel).NOTEFILE)) % nothing in the field... read note file and paste information up on display
                % first check to see if the data file already exists in our database, and if so, just copy the notefile over
                % unless its empty, in which case we can read it first...
                %
                a=strmatch(CONTROL(sel).filename, char(CONTROL.filename));
                b=find(a ~= sel); % find ALL matching entries
                if(~isempty(b)) % explore the possibilities
                    for i=1:length(b)
                        if(~isempty(CONTROL(i).NOTEFILE))
                            CONTROL(sel).NOTEFILE = CONTROL(i).NOTEFILE; % copy it over
                            NOTEFILE = CONTROL(sel).NOTEFILE;
                            pastenote(NOTEFILE, 'NoteFile', DFILE); % update the field from the control list.
                            break; % done with that...
                        end
                    end;
                end;
                if(isempty(CONTROL(sel).NOTEFILE)) % still empty??
                    [path, name, ext, ver] = fileparts(truefile);
                    notefile = fullfile(path, [name, '.not']);
                    QueMessage(sprintf('Parsing Notefile: %s', notefile));
                    notefile = slash4OS(notefile);
                    [NOTEFILE, note_err] = note_read(notefile);
                    if(~note_err)
                        pastenote(NOTEFILE, 'NoteFile', DFILE, name); % also puts up comment field...
                        CONTROL(sel).NOTEFILE=NOTEFILE; % and place it in the CONTROL worksheet...
                        %setuserdata(CONTROL);
                    end
                end;
            else % replace current "NOTEFILE" with the one from the main list
                NOTEFILE = CONTROL(sel).NOTEFILE;
                [path, name, ext, ver] = fileparts(truefile);
                pastenote(NOTEFILE, 'NoteFile', DFILE, name); % update the field from the control list.
            end;
        end;
        %  catch
        %    watchoff;
        %    QueMessage('Error Displaying data from list', 1);
        % end;
        
    case 'zoom'
        h_axes = findobj('tag', 'datawin1');
        if(isempty(h_axes) || ~ishandle(h_axes))
            return;
        end;
        axinfo = get(h_axes, 'UserData'); % There may be information in userdata we can use
        h_info = findobj('tag', 'datawin1_info');
        msg_pos1 = get(h_info, 'pos');
        if(isfield(axinfo, 'down_pos'))
            ax1 = axinfo.down_pos;
            ax2 = axinfo.up_pos;
        else
            return;
        end;
        % and now redraw the display
        u=get(gca, 'YLim');
        if(ax1(1) == ax2(1))
            ax2(1) = ax1(1)+1;
        end;
        if(ax1(2) == ax2(2))
            ax2(2) = ax1(2)+1;
        end;
        xa = sort([ax1(1) ax2(1)]);
        ya = sort([ax1(2) ax2(2)]);
        set(gcf, 'CurrentAxes', h_axes);
        set(gca, 'XLim', xa);
        set(gca, 'Ylim', ya);
        datac_cursorread(-1);

        h_ax2 = findobj('tag', 'datawin0');
        if(ishandle(h_ax2))
            set(h_ax2, 'XLim', xa);
        end;

        switch(DFILE.dmode)
            case 'CC'
                datac_setcrosshair(h_axes, 'datawin1_info', 'ms', 'mV', msg_pos1);
            case 'VC'
                datac_setcrosshair(h_axes, 'datawin1_info', 'ms', 'nA', msg_pos1);
            otherwise
                datac_setcrosshair(h_axes, 'datawin1_info', 'ms', 'mV', msg_pos1);
        end;

    case 'average' % compute average in the window and display it
        h_ax1=findobj('tag', 'datawin1');
        h_ax1 = h_ax1(1);
        if(isempty(h_ax1) || ~ishandle(h_ax1))
            return;
        end;
        time = make_time(DFILE);
        tmax = max(max(time'));
        h_info = findobj('tag', 'datawin1_info');
        msg_pos1 = get(h_info, 'pos');
        tx = get(h_ax1(1), 'XLim'); % get the visible x axis limits
        ti = find_times(tx);
        switch(DFILE.dmode)
            case 'CC'
                avg = mean(VOLTAGE(:,[ti(1):ti(2)]));
            case 'VC'
                avg = mean(CURRENT(:,[ti(1):ti(2)]));
            otherwise
                avg = mean(VOLTAGE(:,[ti(1):ti(2)]));
        end;
        
            STACK = cell(1,1);
        STACK{1} = avg;
        set(gcf, 'CurrentAxes', h_ax1);
        % set(hax1, 'Position', pos1);
        cla;
        hl=line(time(1,ti(1):ti(2))', avg);
        u(1)=min(avg);
        u(2)=max(avg);
        set(gca, 'Ylim', u);
        set(hl, 'color', 'blue');
        datac_cursorread(-1);
        switch(DFILE.dmode)
            case 'CC'
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'mV', msg_pos1);
            case 'VC'
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'nA', msg_pos1);
            otherwise
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'mV', msg_pos1);
        end;

    case 'baseline'
        h_ax1=findobj('tag', 'va_axes1');
        if(isempty(h_ax1) || ~ishandle(h_ax1))
            return;
        end;
        time = make_time(DFILE);
        tmax = max(max(time'));
        axinfo = get(h_ax1, 'UserData'); % There may be information in userdata we can use
        ax1 = axinfo.down_pos;
        ax2 = axinfo.up_pos;
        h_info = findobj('tag', 'datawin1_info');
        msg_pos1 = get(h_info, 'pos');
        switch(DFILE.dmode)
            case 'CC'
                baseline = mean(VOLTAGE(:,[ax1(1):ax2(1)])');
            case 'VC'
                baseline = mean(CURRENT(:,[ax1(1):ax2(1)])');
            otherwise
                baseline = mean(VOLTAGE(:,[ax1(1):ax2(1)])');
        end;
        bflag = 1;
        set(gcf, 'CurrentAxes', h_ax1);
        set(h_ax1, 'Position', msg_pos1);
        cla;
        switch(DFILE.dmode)
            case 'CC'
                for i = 1:size(VOLTAGE,1)
                    hl=line(time(i,:)', VOLTAGE(i,:)-baseline(i));
                end;
            case 'VC'
                for i = 1:size(CURRENT,1)
                    hl=line(time(i,:)', CURRENT(i,:)-baseline(i));
                end;
            otherwise
                for i = 1:size(VOLTAGE,1)
                    hl=line(time(i,:)', VOLTAGE(i,:)-baseline(i));
                end;
        end;
        set(hl, 'color', 'blue');
        datac_cursorread(-1); % update time cursors
        switch(DFILE.dmode)
            case 'CC'
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'mV', msg_pos1);
            case 'VC'
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'nA', msg_pos1);
            otherwise
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'mV', msg_pos1);
        end;

    case 'unzoom' % rescale the data to "show all"
        h_ax1=findobj('tag', 'datawin1');
        if(isempty(h_ax1) || ~ishandle(h_ax1))
            return;
        end;
        time = make_time(DFILE);
        tmax = max(max(time'));
        set(h_ax1, 'XLim', [0 tmax]);
        h_info = findobj('tag', 'datawin1_info');
        msg_pos1 = get(h_info, 'pos');
        % set(hax1, 'Position', pos1);
        switch DFILE.dmode
            case 'CC'
                vmax = max(max(VOLTAGE));
                vmin = min(min(VOLTAGE));
            case 'VC'
                vmax = max(max(CURRENT));
                vmin = min(min(CURRENT));
            otherwise
                vmax = max(max(VOLTAGE));
                vmin = min(min(VOLTAGE));
        end;
        u = [vmin vmax];
        set(h_ax1, 'YLim', u);
        datac_cursorread(-1); % update time cursors
        switch(DFILE.dmode)
            case 'CC'
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'mV', msg_pos1);
            case 'VC'
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'nA', msg_pos1);
            otherwise
                datac_setcrosshair(h_ax1, 'datawin1_info', 'ms', 'mV', msg_pos1);
        end;
        avg = [];
        bflag = 0;
        return;
        
    case 'rawtraces'
        plot_data(DFILE, 1);

    case 'storecursors'   % put the cursor information into the psp_time array if it is available.
        sf = getmainselection;
        if(length(sf) > 1)
            return;
        end;
        CONTROL(sf).psp_time = sprintf('[%s]', sprintf('%7.2f ',TMARKS.t));
        return;

    case 'retrieve' % get a record (list) from the current file, display it. Second argument has the record list
        erase_data_axes;
        [truefile, RL, mode] = getfileinfo('Manual', DFILE, PATHFLAG);
        h2 = findobj('Tag', 'Path');
        path = get(h2, 'String');
        try
            watchon;
            [DFILE, err] = readdatac_window(truefile, ctl, [], 0, mode, 1);
            watchoff;
        catch
            watchoff;
        end;
    case 'erase' % calls erase data axes
        erase_data_axes;


        %  profile viewer
    case 'selectall' % select all the entries in the list and show us
        hc = findobj('tag', 'CTL');
        set(hc, 'value', [1:get(hc, 'max')]) % this selects ALL entries

    case 'unselect' % deselect all the entries in the list
        hc = findobj('tag', 'CTL');
        set(hc, 'Value', get(hc, 'listboxtop')); % essentially clear existing selection - selects current top entry.

    case  'scan'
        if(check_scan_status == 1) % check to see if we're "running"
            Set_scan_status('off');
            return;
        end
        [truefile, RL, mode] = getfileinfo ('Manual', DFILE);
        truefile = slash4OS(truefile);
        [DFILE, data, err] = datac2mat(truefile, []); % just read the header - empty RL list
        [pwin]=make_data_window;
        RL=1:DFILE.records_in_file;
        subplot('position', [0.1 0.4 0.8 0.45]);
        subplot('position', [0.1 0.1  0.8 0.25]);

        hsub=get(gcf, 'Children');
        subplot(hsub(1));
        subplot(hsub(2));

        Set_scan_status('on');
        watchon;
        for i=1:length(RL)
            if(check_scan_status == 0)  % if it says "scan", then stop!
                break;
            end
            [DFILE, data, err] = datac2mat(truefile, RL(i));
            if(i==1)
                time=0:(DFILE.rate*DFILE.nr_channel)/1000:((DFILE.nr_points-1)*DFILE.nr_channel*DFILE.rate)/1000;
            end

            if(err == 1) return;
            end

            DFILE.junctionpot = 0;
            DFILE.vgain = 10;
            DFILE.igain = 1;
            DFILE.wgain = 1;

            scaledat(DFILE, data);

            % make simple plot here

            subplot(hsub(2));
            plot(time, VOLTAGE, 'EraseMode', 'Background');
            axis manual;
            axis([0 200 -140 40]);
            subplot(hsub(1));
            plot(time, CURRENT, 'EraseMode', 'Background');
            axis manual;
            axis([0  200 -1500 1500]);
            drawnow;

        end
        Set_scan_status('off');
        watchoff;

    case 'newctl' % clear the control worksheet - Database New
        try
            if(~isempty(MATFILE))
                read_control('save', MATFILE);  % first save any existing file
            else
                [r,t,err] = datac('saveasmatctl'); % save the database as a new file
                if(err)
                    return;
                end;
            end;
        catch
            QueMessage('Database save Failed?', 1);
            err = 1;
            return;
        end;
        CONTROL=[]; % clear the file
        MATFILE=[]; % clear the associated filename
        ctlfile = '<new>';
        ctlpath = '';
        clearlist;
        new_banner(DATAFILE, MATFILE);
        return;

    case 'importctl'

        [ctlfile, ctlpath] = uigetfile('c:\Origin50\projects\*.txt', 'Open Origin Control Files');
        if(ctlfile == 0)
            err = 1;
            return;
        end
        ctlname = strcat(ctlpath, ctlfile);
        [CONTROL, NSF, err]=read_control('import', ctlname);
        setlist;
        return

    case 'import_from_summary'
        [ctlfile, ctlpath] = uigetfile('\mat_datac\*.mat', 'Open Summary File');
        if(ctlfile == 0)
            err = 1;
            return;
        end
        ctlname = strcat(ctlpath, ctlfile);
        [CONTROL, NSF, err]=read_control('import_from_summary', ctlname);
        setlist;
        return

    case 'readmatctl'
        QueMessage(' ', 1);
        dbfile = slash4OS([PATHS.BP '/ExperimentSummary']);
        cdir = pwd;
        cd(dbfile);
        [ctlfile, ctlpath] = uigetfile('*.mat', 'Open Matlab Database Files');
        cd(cdir);
        if(ctlfile == 0)
            err = 1;
            return;
        end
        ctlname = strcat(ctlpath, ctlfile);
        clearlist;
        try
            [NSF, err]=read_control('open', ctlname);
        catch
            QueMessage('datac: Error opening database', 1);
            return;
        end;

        h2=findobj('Tag', 'CTL'); % first get the selection number
        set(h2, 'Value', []); % clear the selection list to one value (hopefully the list is that long).
        setlist;
        MATFILE = ctlname;
        h=findobj('Tag', 'CtlFile'); % get the menu tag to indicate the current file
        set (h, 'Label', sprintf('Open Expt: %s', MATFILE));
        h=findobj('Tag', 'CTL');
        set (h, 'TooltipString', sprintf('Select from Experiments in %s', MATFILE));
        new_banner(DATAFILE, MATFILE);
        return

    case 'loadmatctl' % pass the complete filename in ctl
        clearlist;
        dbfile = slash4OS([PATHS.BP '/ExperimentSummary']);
        cdir = pwd;
        cd(dbfile);
        [NSF, err]=read_control('open', ctl);
        cd (cdir);
        if(err ~= 0) % check for error - like can't get file
            result = err;
            return;
        else
            h2=findobj('Tag', 'CTL'); % first get the selection number
            set(h2, 'Value', []); % clear the selection list to one value (hopefully the list is that long).
            setlist;
            MATFILE = ctl;
            h=findobj('Tag', 'CtlFile'); % get the menu tag to indicate the current file
            set (h, 'Label', sprintf('Open Expt: %s', MATFILE));
            new_banner(DATAFILE, MATFILE);
            h=findobj('Tag', 'CTL');
            set (h, 'TooltipString', sprintf('Select from Experiments in %s', MATFILE));
            return;
        end;

    case 'saveasmatctl' % save as...
        dbfile = slash4OS([PATHS.BP '/ExperimentSummary']);
        cdir = pwd;
        cd(dbfile);
        [ctlfile, ctlpath] = uiputfile('*.mat', 'Save Control Files in MAT format');
        cd(cdir);
        if(ctlfile == 0) % no file selected
            err = 1;
            return;
        end
        ctlname = strcat(ctlpath, ctlfile);
        watchon;
        read_control('save', ctlname);
        watchoff;
        MATFILE = ctlname;
        QueMessage(sprintf('Saved control matrix in %s', ctlname));
        return

    case 'savematctl' % save to same file without asking...
        if(isempty(MATFILE))
            QueMessage(' Cannot save - no file');
            return;
        end
        dbfile = slash4OS([PATHS.BP '/ExperimentSummary']);
        cdir = pwd;
        cd(dbfile);
        read_control('save', MATFILE);
        cd(cdir);
        QueMessage(sprintf('Saved control matrix in %s', MATFILE));
        return;

    case 'resequence' % recompute the sequence numbers for the whole file (for sorting....)
        for i = 1:length(CONTROL)
            [p, fn, e] = fileparts(CONTROL(i).filename);
            seq = make_sequence(fn, min(seqparse(CONTROL(i).reclist)));
            CONTROL(i).seqname = seq;
        end;
        setlist;

    case 'sortcontrol'
        QueMessage('Sorting ...', 1);
        u(1,:) = (number_arg({CONTROL.seqname}));

        [b, index] = sortrows(u', [1]); % get the indices - use for copy of elements
        for i=1:length(u)
            newc(i) = CONTROL(index(i));
        end
        CONTROL = newc;
        setlist;
        QueMessage('Sorted', 1);

    case 'sortbypnd'
        QueMessage('Sorting ...', 1);
        % sorts both by pnd and then by div...
        u(1,:)=number_arg({CONTROL.pnd}); %
        u(2,:) = number_arg({CONTROL.div});

        [b, index] = sortrows(u', [1,2]); % get the indices - use for copy of elements
        for i=1:length(u)
            newc(i) = CONTROL(index(i));
        end
        CONTROL = newc;
        setlist;
        QueMessage('Sorted', 1);

    case 'sortbyExpt'
        % sorts both by Expt and then by Group1 and finally by Group 2...
        QueMessage('Sorting ...', 1);
        u(1,:)=number_arg({CONTROL.E_C}); %
        u(2,:)=number_arg({CONTROL.G1}); %
        u(3,:) = number_arg({CONTROL.G2});

        [b, index] = sortrows(u', [1,2,3]); % get the indices - use for copy of elements
        for i=1:length(u)
            newc(i) = CONTROL(index(i));
        end
        CONTROL = newc;
        setlist;
        QueMessage('Sorted', 1);

    case 'dupe' % search for and remove duplicates from the CONTROL list
        modctl=dupe(CONTROL);
        if(~isempty(modctl))
            CONTROL=modctl;
            setlist;
        end
    case 'pickpath'
        hp  = findobj('tag', ctl);
        if(isempty(hp))
            fprintf(1, 'datac(pickpath): no object with tag %s\n', ctl);
            return;
        end;
        cpath = get(hp, 'string');
        directory_name = uigetdir(cpath,'Pick Data Path');
        if(directory_name)
            set(hp, 'string', directory_name);
        end;
            
        
        
    case 'updatepaths' % try to update the path information in the control file
        makenewpath;
        setlist;

    case 'unixupdatepaths' % version that runs only on unix-based systems with a find command...
        hp = findobj('tag', 'Path');
        basepath = get(hp, 'String');
        cmd = sprintf('find %s | grep ''[a-z0-9]*\\.mat''\n', basepath);
  %      cmd
        [status, files]=system(cmd);
  %      status
        % files now contains all the data files found in on and below that
        % path.
        % break string into each file found.
        [u j] = find(files == 10);
        si = 1;
        nf = 1;
        pf = cell(length(j), 1);
        pa = cell(length(j), 1);
        for i = j
            cfile = files(si:i-1);
            [p f e] = fileparts(cfile);
            pa{nf} = p;
            pf{nf} = [f e];
            si = i+1;
            nf = nf+1;
        end;
        sf=getmainselection;
        for i = 1:length(sf)
            k = strmatch(CONTROL(sf(i)).filename, pf, 'exact');
            if(k > 0)
                CONTROL(sf(i)).path = pa{k};
                fprintf(1, 'File %s path set to: %s\n', CONTROL(sf(i)).filename, pa{k});
            else
                fprintf(1, 'File: %s  not found\n', CONTROL(sf(i)).filename);
            end;
        end;


    case 'unixupdatepaths_old' % version that runs only on unix-based systems with a find command...
        sf=getmainselection;
        searched = cell(1,1);
        spath = cell(1,1);
        j = 0;
        for i = 1:length(sf)
            k = strmatch(CONTROL(sf(i)).filename, searched, 'exact');
            if(k > 0)
                CONTROL(sf(i)).path = spath{k};
            else
                cmd =  sprintf('find /users/pmanis/desktop/CurrentProjects -name "%s"', CONTROL(sf(i)).filename);
                [a, d] = system(cmd);
                if(~isempty(d) && a == 0)
                    [p] = fileparts(d);
                    CONTROL(sf(i)).path=p;
                    fprintf(1, 'File: %s  found in %s\n', CONTROL(sf(i)).filename, p);
                    j = j + 1;
                    searched{j} = CONTROL(sf(i)).filename;
                    spath{j} = p;
                else
                    fprintf(1, 'File: %s  not found\n', CONTROL(sf(i)).filename);
                end;
            end;
        end;

    case 'editcontrol'
        edit_control('edit'); % call the editor
        return;

    case 'bridge_adjust'
        bridge_new(ctl, DFILE); % just pass it on with the data...

    case 'Notefile'
        % make a filename to open the note file (assumes superpad resides at c:\windows\superpad.exe)
        htag = findobj('Tag', 'CTL');
        sf = get(htag, 'Value');
        sf = sf(1); % only allow the first selection
        truefile = strcat(append_backslash(CONTROL(sf).path), CONTROL(sf).filename);
        [path, name, ext, ver] = fileparts(truefile);
        if(strcmp(computer, 'PCWIN'))
            if(sf>1) % there is a control list - use that to access data
                path=drive_subst(path);
            end
            notefile = fullfile(path, [name, '.not']);
            try
                eval(['!c:\windows\superpad.exe ', notefile]);
            catch
                QueMessage('Can''t find superpad', 1);
            end;

        else
            notefile=fullfile(path, [name, '.not']);
            eval(sprintf('!nedit %s &', lower(notefile)));
        end

    case 'ViewNote'
        h2=findobj('Tag', 'CTL'); % first get the selection number
        bigsel = get(h2, 'Value');
        % nargin is at least 2 - use the nth (defined by ctl) selection...
        okfile = 0;
        if(~isempty(bigsel))
            sel = bigsel(1); % can only view one at a time...
            if(sel <= length(CONTROL))
                truefile = parse_filename(CONTROL(sel).path, CONTROL(sel).filename); % get the filename like this...
                okfile = 1;
            end;
        end
        if(~okfile)
            truefile = DFILE.fullfile; % use current input
        end;
        [path, name, ext, ver] = fileparts(truefile);
        if(~strcmp(ext, '.mat'))
            notefile = fullfile(path, [name, '.not']);
        else
            notefile = fullfile(path, [name, ext]);
        end;
        pfn(notefile);


    case 'NoteInFile'
        [drive, path, ext] = getdriveext;
        lookpath=strcat(path, ext);
        [filename, path] = uigetfile(lookpath, 'View Info from Data File');
        if(~ischar(filename))
            QueMessage(sprintf('Unable to access file?'));
            result = 1;
            return;
        end
        setdriveext('path', path);
        LASTPATH = path;
        lookpath = path;
        truefile = strcat(path, filename);
        [path, name, ext, ver] = fileparts(truefile);
        if(~strcmp(ext, '.mat'))
            notefile = fullfile(path, [name, '.not']);
        else
            notefile = fullfile(path, [name, ext]);
        end;
        pfn(notefile);

    case 'ToControl'
        dtype=[];
        to_control(DFILE, NOTEFILE, dtype); % basic - just the selected record in the list...
        watchoff;

    case 'Duplicate'
        h2=findobj('Tag', 'CTL'); % first get the selection number
        bigsel = get(h2, 'Value');
        for i = 1:length(bigsel)
            sel = bigsel(i);
            l = length(CONTROL);
            CONTROL(l+1) = CONTROL(sel);
        end;
        datac('sortcontrol'); % sort the data base anew.

    case 'AddProtocol'
        prompt  = 'Protocol Name ';
        title   = 'Select Protocol' ;
        lines= 1;
        answer  = inputdlg(prompt,title,lines);
        if(~isempty(answer))
            to_control(DFILE, NOTEFILE, answer);
        end;

    case 'UpdateNoteFile'
        [bigsel, lmode] = listcontrol(PATHFLAG); % get the info from the selection
        % nargin is at least 2 - use the nth (defined by ctl) selection...
        for i = 1:length(bigsel) % handle multiple selections...
            sel = bigsel(i);
            truefile = parse_filename(CONTROL(sel).path, CONTROL(sel).filename); % get the filename like this...
            [path, name, ext, ver] = fileparts(truefile);
            if(~strcmp(ext, '.mat'))
                notefile = fullfile(path, [name, '.not']);
            else
                notefile = fullfile(path, [name, ext]);
            end;
            QueMessage(sprintf('Parsing Notefile for: %s', CONTROL(sel).filename));
            [NOTEFILE, note_err] = note_read(notefile);
            if(~note_err)
                pastenote(NOTEFILE, 'NoteFile', DFILE); % also puts up comment field...
                CONTROL(sel).NOTEFILE=NOTEFILE; % and place it in the CONTROL worksheet...
                %         setuserdata(CONTROL);
            end
        end;


    case 'Tag' % tag the selected entry for analysis
        if(~isfield(CONTROL, 'Tag'))
            [CONTROL.Tag] = deal(0);
        else
            sel = getmainselection;
           [CONTROL(sel).Tag] = deal(1);
        end;
        setlist;

    case 'unTag' % untag the selected entry for analysis
        if(~isfield(CONTROL, 'Tag'))
            [CONTROL.Tag] = deal(0);
        else
            sel = getmainselection;
           [CONTROL(sel).Tag] = deal(0);
        end;
        setlist;

    case 'DB_Extract'
        % extract selected entries into a new data base.
        datac('savematctl'); % first save the current data base.
       sel = getmainselection;
        if(~isempty(sel))
            [p f e] = fileparts(MATFILE); % prevent from having the same name
            f = [f '(extracted)'];
            MATFILE = fullfile(p, [f e]); % give it a new name
            CONTROL = CONTROL(sel);
            set(h2, 'Value', 1); % set at top of list;
            setlist;
            new_banner(DATAFILE, MATFILE);
        end;
   
    case 'Combine' 	% combine entries: just put records from all into the first, and
        % then delete the remainder. Assume first knows everything
        h2=findobj('Tag', 'CTL'); % first get the selection number
        sel = getmainselection;
        if(length(sel) >= 2) % must have something to combine in selection...
            fnames=fieldnames(CONTROL);
            i = sel(1); % put in the first place
            CONTROL(i).reclist=sprintf('%d;%d', CONTROL(i).recbeg, CONTROL(i).recend);
            CONTROL(i).recbeg=[]; CONTROL(i).recend=[];

            for j=sel(2:length(sel)) % copy the information to the main record
                disp(sprintf('> j: %d F: %s  rlist: %s  rbeg: %d', j, CONTROL(j).filename, ...
                    CONTROL(j).reclist, CONTROL(j).recbeg))
                CONTROL(i).reclist=sprintf('%s,%d;%d', CONTROL(i).reclist,...
                    CONTROL(j).recbeg, CONTROL(j).recend);
            end;
            [CONTROL, sf] = del_record(h2, CONTROL, sel(2:length(sel))); % delete all but first in selectin list
        end;
        
    case 'Collect'  % collect entries: like combine, but does all entries with the
        % same filename and protocol, then deletes all but the first.
        h2=findobj('Tag', 'CTL'); % first get the selection number
        done = 0;
        pos = 1;
        fnames=fieldnames(CONTROL);
        while(~done)
            if(pos > length(CONTROL))
                done = 0;
                break;
            end;
            fsel = [];
            psel = [];
            for i = pos:length(CONTROL)
                if(strcmp(CONTROL(pos).filename, CONTROL(i).filename))
                    fsel = [fsel i];
                end;
                if(strcmp(CONTROL(pos).protocol, CONTROL(i).protocol))
                    psel = [psel i];
                end;
            end;
            sel = intersect(fsel, psel);
            if(length(sel) > 1)
                disp(sprintf('collecting : %d', sel))
                i = sel(1) % put in the first place
                CONTROL(i).reclist=sprintf('%d;%d', CONTROL(i).recbeg, 			CONTROL(i).recend);
                CONTROL(i).recbeg=[]; CONTROL(i).recend=[];
                for j=sel(2:length(sel)) % copy the information to the main record
                    disp(sprintf('> j: %d F: %s  rlist: %s  rbeg: %d', j, CONTROL(j).filename, ...
                        CONTROL(j).reclist, CONTROL(j).recbeg))
                    CONTROL(i).reclist=sprintf('%s,%d;%d', CONTROL(i).reclist,...
                        CONTROL(j).recbeg, CONTROL(j).recend);
                end;
                [CONTROL, sf] = del_record(h2, CONTROL, sel(2:length(sel))); % delete all but first in selectin list
                %        setuserdata(CTL);
            end;
            pos = pos + 1;
        end; % of the while.



    case 'DeleteControl' % delete selected element from the control list
        h2 = findobj('Tag', 'CTL');
        sel = getmainselection;
        answer = questdlg('Are You Sure You want to Delete these entries?', 'Yes - Delete!', 'No');
        if(strcmp(answer, 'Yes'))
            entry = sprintf('%s [R:%d]', CONTROL(sel).filename, CONTROL(sel).recbeg);
            [CONTROL, sf] = del_record(h2, CONTROL, sel);
            QueMessage(sprintf('Entry %d = %s deleted', sel, entry));
        end;
        setlist;

    case 'Toggle'
        toggle_display('Toggle');
        return;

    case 'FileInfo' % use html to generate a formatted listing of file information
        htag = findobj('Tag', 'CTL');
        sf = get(htag, 'Value');
        for i = 1:length(sf)
            truefile = strcat(append_backslash(CONTROL(sf(i)).path), CONTROL(sf(i)).filename);
            [path, name, ext, ver] = fileparts(truefile);
           if(~strmatch(ext, '.mat', 'exact'))
                ext = '.not';  % replace with '.not' extension
            end;
            if(strcmp(computer, 'PCWIN'))
                if(sf(i)==0) % there is a control list - use that path to access the data
                    path=drive_subst(path);
                end
                notefile = fullfile(path, [name ext]);
            else
                h2 = findobj('Tag', 'Path');
                path = get(h2, 'String');
                notefile=lower(fullfile(path, [name, '.not']));
            end
            pfhtml(notefile);
        end;

    case 'ParseNote' % uses current notefile to parse
        %   CONTROL = getuserdata;
        % make a filename to open the note file (assumes superpad resides at c:\windows\superpad.exe)
        sf = getmainselection;
        truefile = strcat(append_backslash(CONTROL(sf).path), CONTROL(sf).filename);
        [path, name, ext, ver] = fileparts(truefile);
        if(strcmp(computer, 'PCWIN'))
            if(sf>1) % there is a control list - use that to access data
                path=drive_subst(path);
            end
            notefile = fullfile(path, [name, '.not']);
        else
            h2 = findobj('Tag', 'Path');
            path = get(h2, 'String');
            notefile=lower(fullfile(path, [name, '.not']));
        end
        QueMessage(sprintf('Reading Notefile: %s', notefile));
        [NOTEFILE, note_err] = note_read(notefile);
        if(note_err > 0)
            watchoff;
            return;
        end
        pastenote(NOTEFILE, 'NoteFile', DFILE, notefile);
        watchoff;


    case 'SetPath'
        [drive, path, ext] = getdriveext;
        setpath(path);


    % Basic VC analyses.....

    case 'vc_iv'
        VC_IV;

        % basic CC analyses
    case 'cc_iv'
        CC_IV(ctl);

        % basic EPSC analyses
    case 'epsc_analysis'
        EPSC_mini;

    case 'epsc_io'
        EPSC_IO;


        % EPSP covariance analysis
    case 'epsc_covariance'
        EPSC_COV;

    case 'epsc_rect'
        EPSC_Rect;

    case 'sc' % single channel
        try
            QueMessage('SC analysis', 1); % clear the que
           sf=getmainselection; % this sould be in the sc file itself... 
            if(sf <= 0) return;
            end
            for i = 1:length(sf)
                SC(DFILE, sf(i), 1); % single channel analysis...
            end;
        catch
            watchoff;
            QueMessage('Error in Single-Channel Analysis routine', 1);
        end;


    case 'Trace_View'
        try
            sf = getmainselection;
            if(sf > 0)
                pflag = getplotflag;
                QueMessage('Trace View', 1); % clear the que
                for i = 1:length(sf)
                    trace_view(0, sf(i), pflag);
                end;
            end;
        catch
            watchoff;
            QueMessage('Error in Trace  View routine', 1);
        end;

        % analysis of spike conditioning paradigms.
    case 'fwd'
        FWD;

    case 'sta_avg'
        STA;

        % basic EPSP time course analyses
    case 'epsp_tc'
        EPSP_TC;


        % basic intrinsic time course analyses
    case 'int_tc'
        try
            %      CONTROL = getuserdata;
            sf = getmainselection;
            if(sf <= 0) return;
            end
            QueMessage('INT_TC analysis', 1); % clear the que
            for i = 1:length(sf)
                TC_INT(sf(i), 1);
            end;
        catch
            watchoff;
            QueMessage('Error in INT_TC Analysis routine', 1);
        end;

        % basic FP time course analyses
    case 'fp_tc'
        try
            sf = getmainselection;
            if(sf <= 0) return;
            end
            pflag = getplotflag;
            QueMessage('FP_TC analysis', 1); % clear the que
            for i = 1:length(sf)
                FP_TC(DFILE, sf(i), pflag);
            end;
        catch
            watchoff;
            QueMessage('Error in Field Potential TC Analysis routine', 1);
        end;

        % basic FP input-output analyses
    case 'fp_io'
        try
            sf = getmainselection;
            if(sf <= 0) return;
            end
            pflag = getplotflag;
            QueMessage('FP_IO analysis', 1); % clear the que
            for i = 1:length(sf)
                FP_IO(DFILE, sf(i), pflag);
            end;
        catch
            watchoff;
            QueMessage('Error in Field Potential IO Analysis routine', 1);
        end;

    case 'artsuppv' % suppress artifacts in voltage trace (modifies VOLTAGE)
        fprintf(1, 'artsuppv\n');
        sf = getmainselection;
        artifact_threshold = 300;
        [vfp, stim_time] = FP_artsupp(VOLTAGE, DFILE, sf(1), 1, artifact_threshold);
        if(~isempty(vfp))
            ALLCH{1} = vfp;
            VOLTAGE=vfp;
        end;
        plot_data(DFILE, 1);
    
           case 'artsuppi' % suppress artifacts in voltage trace (modifies VOLTAGE)
        sf = getmainselection;
        artifact_threshold = 2000;
        [vfp, stim_time] = FP_artsupp(CURRENT, DFILE, sf(1), 1, artifact_threshold);
        if(~isempty(vfp))
            ALLCH{2} = vfp;
            CURRENT=vfp;
        end;
        plot_data(DFILE, 1);
 
        % basic VC time course analyses
    case 'vc_tc'
        try
            sf = getmainselection;
            if(sf <= 0) return;
            end
            QueMessage('VC_TC analysis', 1); % clear the que
            for i = 1:length(sf)
                VC_TC(sf(i), 1);
            end;
        catch
            watchoff;
            QueMessage('Error in VC_TC Analysis routine', 1);
        end;

        % exponential fitting routines
    case 'fitEPEE1'
        QueMessage('EPEE1', 1); % clear the que
            sf = getmainselection;
        if(sf <= 0)
            return;
        end
        STEPS = find_steps(DFILE, 'v', 1);
        for i = 1:length(sf)
            [tctab, vtab, modctl] = EPEE_fit(DFILE, CONTROL, sf(i), STEPS, 1);
        end

    case 'fitEPEE2'
        QueMessage('EPEE2', 1); % clear the que
            sf = getmainselection;
        if(sf <= 0)
            return;
        end;
        STEPS = find_steps(DFILE, 'v', 1)
        for i = 1:length(sf)
            [tctab, vtab, modctl] = EPEE_fit(DFILE, CONTROL, sf(i), STEPS, 2);
        end

    case 'fitEPEE3'
        QueMessage('EPEE3', 1); % clear the que
            sf = getmainselection;
        if(sf <= 0) return;
        end
        STEPS = find_steps(DFILE, 'v', 1);
        for i =length(sf)
            [tctab, vtab, modctl] = EPEE_fit(DFILE, CONTROL, sf(i), STEPS, 3);
        end;

    case 'VCset' % set vc parameters on selected data.
        set_vcpar;

    case 'CCset' % set vc parameters on selected data.
        set_ccpar;

    case 'setlist' % just call the private function
        setlist;

    case 'addwindow'
        if(isempty(WINDOWLIST))
            WINDOWLIST = {};
        end;
        WINDOWLIST = cat(1, WINDOWLIST, {ctl});

    case 'EXIT'
        getsetini('set', MATFILE);
        % close all the open windows. To avoid problems with other pssibly running programs,
        % we look for the specific tags here
        win = {'datac_main', 'CC_IV', 'VC_IV', 'EPSP_TC', 'TC_INT', 'APWave', 'STA_spec', 'STA_spiketrain', ...
            'STA_specgm', 'CC_IV_spiketrain', 'Comparison', 'ParamEdit'};
        for i = 1:length(win)
            h = findobj('Tag', win{i});
            if(ishandle(h))
                delete(h); % get out...
            end;
        end;
        for i = 1:length(WINDOWLIST)
            h = findobj('Tag', WINDOWLIST{i});
            if(ishandle(h))
                delete(h); % get out...
            end;
        end;
        if(~isempty(OLDDIR))
            cd(OLDDIR);
        end;
        
    case 'ImportNeuron' % convert neuron files to datac format file
        try
            nrn2datac;
        catch
            watchoff;
            QueMessage('Error in Neuron Import routine', 1);
        end;


    case 'ImportRTXI' % convert neuron files to datac format file
        try
            rtxi2datac;
        catch
            watchoff;
            QueMessage('Error in RTXI Import routine', 1);
        end;

    otherwise
        QueMessage(sprintf('Case for %s not found!', command), 1);
        return
end
return;

%---------------------

function new_banner(DF, MF)
% update the top banner for the program.
h = findobj('Tag', 'datac_main'); % handle to the main window
if(~ishandle(h))
    return;
end;
if(isempty(DF))
    fn = 'No file';
else
    [p f e] = fileparts(DF);
    fn = [f e];
end;
if(isempty(MF))
    mn = 'No Database';
else
    [p f e] = fileparts(MF);
    mn = [f e];
end;
set(h, 'name', sprintf('Datac Analysis  -  DB: %s   File: %s', mn, fn));
return;




% *****************************************************************
%
% *****************************************************************

% delete a single record from the list
% delete a single record from the list

function [CTLOUT, sf] = del_record(h2, CONTROL, sel)
% make the modifed data available.....
n = [1:length(CONTROL)];
CTLOUT = CONTROL(setxor(n, sel));
lm = length(CTLOUT);
setuserdata(CTLOUT);
% now update the visible list
setlist;
toggle_display('List');
sf=min(sel)-1;
if(sf > lm - 1) % make sure the selection is within the list
    sf = lm - 1;
elseif (sf < 1)
    sf = 1;
end;
h1=findobj('Tag', 'CTL');
if(ishandle(h1))
    set(h1, 'Value', sf); % select the new argument below the first argument
    if(sf > 15)
        set(h1, 'ListboxTop', sf-5); % scroll the list so new one is in view
    else
        set(h1, 'ListboxTop', 1); % unles its just a short list, then just set to top.
    end
end;
return;


function clearlist()
htag=findobj('Tag', 'CTL');
if(ishandle(htag))
    set(htag, 'Max', 0);
    set(htag, 'String', '');
end;
return;


% *****************************************************************
%
% *****************************************************************
function [status] = check_scan_status()
% read the title on the button to identify status...
htag=findobj('Tag', 'Scan');
if(ishandle(htag))
    status = get(htag, 'String');
    if(strcmp('Scanning', status))
        status = 1;
    else
        status = 0;
    end
end;
return

% *****************************************************************
%
% *****************************************************************
function Set_scan_status(arg)

htag=findobj('Tag', 'Scan');
status = get(htag, 'String');
switch (arg)
    case 'on'
        set(htag, 'String', 'Scanning');
        %disp('Scanning turned On');
    case 'off'
        set(htag, 'String', 'Scan');
        %disp('Scanning turned off');
    otherwise
end


% *****************************************************************
%
% *****************************************************************
function toggle_scan_status();

status = check_scan_status;
htag=findobj('Tag', 'Scan');
if(status == 1)
    set(htag, 'String', 'Scan'); % restore button
    QueMessage('Scanning turned off');
    return;
else
    set(htag, 'String', 'Scanning');
    QueMessage ('Scanning going');
end
return

% *****************************************************************
%
% *****************************************************************
function [truefile, RL, mode, err] = getfileinfo(how, dfile, pathflag)
err=0;
mode=getdatamode;
RL=[1:2];
if(~isempty(dfile))
    truefile = parse_filename(dfile.path,dfile.filename);
    truefile=strcat(truefile, dfile.ext);
else
    truefile='';
end

switch (how)
    case 'Manual'
        htag=findobj('Tag', 'RecList');
        RecList=get(htag, 'String');
        [RL, err] = record_parse(RecList);
        if(err)
            QueMessage('Unable to evaluate record list');
            return;
        end
        mode = getdatamode; % read the mode from the display
    case 'Note'
        truefile=dfile.fullfile;
        htag = findobj('Tag', 'NoteFile');
        sel = get(htag, 'Value');
        string = cellstr(get(htag, 'String'));
        sstr = char(string(sel(1))); % if multiple selection, we only show one...
        if(~strcmp(sstr(1), '>')) % check for selection of the note instead of the data
            err=1;
            return;
        end
        A = sscanf(char(sstr), '> %d %d');
        RL=A(1):A(2);
        % try to figure out data mode from A(3) : cciv, hyp, hyp2, tc mean CC
        switch (sstr)
            case {'cciv', 'hyp2', 'hyp', 'tc', 'ap-iv', 'ap_iv', 'ap-iv2', 'ap-iv2', 'hypwatch', 'noise500'}
                mode = 'CC';
            otherwise
                mode = 'VC';
        end;
    otherwise
end
return;


% *****************************************************************
%
% *****************************************************************
function [pwin] = make_data_window()

pwin = findobj('Tag', 'Data_Win');
if ishandle(pwin)
    return; % one exists  - so use it
end
scrsz = get(0,'ScreenSize');
scrwd = scrsz(3)/3;
scrht = scrsz(4)/3;
scrl = scrsz(1)+(scrsz(3)*0.1);
scrb = scrsz(2)+(scrsz(4)*0.55);
pwin = figure('Color', 'white', ...
    'Colormap',[1,1,1], ...
    'Position', [scrl, scrb, scrwd, scrht], ...
    'Tag','Data_Win');
return


function erase_data_axes()

axlist = {'top_plot', 'bottom_plot', 'third_plot'};
for i = 1:length(axlist)
    h = findobj('tag', axlist{i});
    if(~isempty(h) && ishandle(h))
        axes(h);
        cla;
    end;
end;

drawnow;
return;

